import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

//实现线程池
class MyThreadPool{
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private int maxPoolSize = 0;
    private List<Thread> threadList = new ArrayList<>();

    public MyThreadPool(int corePoolSize,int maxPoolSize){//这里的 corePoolSize 是核心线程数量
        //初始化 消费者
        //创建若干个线程,n个
        for (int i = 0; i <corePoolSize ; i++) {
            Thread t = new Thread(()->{
                try {
                    while (true) {
                       Runnable runnable = queue.take();
                        runnable.run();
                    }
                } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                }
            });
            t.start();
            threadList.add(t);
        }
    }
    void submit(Runnable runnable) throws InterruptedException {
        //把任务添加到线程中
        //此处进行判定,判定当前任务队列的元素个数,是否比较长
        //如果队列元素比较长,说明已有的线程,不太能处理过来了,创建新的线程即可
        //如果队列不是很长,没必要创建新的线程
        queue.put(runnable);
        if(queue.size()>=500&&threadList.size()<=maxPoolSize){
            //阈值比较灵活
            Thread t = new Thread(()->{
                try {
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        //生产者
        MyThreadPool threadPool = new MyThreadPool(10,20);
        for (int i = 0; i <10000 ; i++) {
            //这个循环只是 submit 任务到阻塞队列中,有十个线程来消费队列中的任务
            //主线程在这里只是添加任务
            int id = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello" + id +","+Thread.currentThread().getName());
                }
            });
        }
    }
}
